<template>
	<view class="login">
		<view class="title">欢迎登录</view>
		<view class="username">
			用户名
		</view>
		<u-form labelPosition="left" :model="info" :rules="rules" ref="uFormRef" labelWidth="0">
			<u-form-item prop="username">
				<u-input v-model="info.username" placeholder="请输入账号" border="bottom"></u-input>
			</u-form-item>
			<view style="height:30rpx"></view>
			<u-form-item prop="password">
				<u-input v-model="info.password" placeholder="请输入密码" border="bottom" password></u-input>
			</u-form-item>
		</u-form>
		<view class="btn">
			<u-button type="primary" text="登 录" shape="circle" color="#e71f17" @click="onSubmit"></u-button>
		</view>
		<view class="username">
			请使用账号密码登录。
		</view>
	</view>
</template>

<script setup>
  import { onLoad } from '@dcloudio/uni-app';
	import { ref, reactive } from 'vue';
	import { useLoginStore } from '@/stores/login';

	const info = reactive({
		username: '',
		password: '',
	})

	const rules = reactive({
		'username': [{
				type: 'string',
				required: true,
				message: '请输入手机号',
				trigger: ['blur'],
			},
		],
		'password': {
			type: 'string',
			required: true,
			message: '请输入密码或验证码',
			trigger: ['blur'],
		},
	})

	const uFormRef = ref(null); // 表单引用

	const loginStore = useLoginStore();

  onLoad(() => {
    if (loginStore.isLogin) {
      uniLoginRefresh(loginStore.userInfo.openId);
    }
  });

	async function onSubmit() {
		try {
			// 校验是异步的
			await uFormRef.value?.validate()
      const { token } = await uni.$api.wxLoginBinding({
        ...info,
        openId: loginStore.userInfo.openId
      });
      uni.setStorageSync('token', token);
      const res = await uni.$api.getUserInfo();
      loginStore.setUserInfo({token, isBinding: '1', ...res.data});
      await loginStore.setAccessToken();
      await uni.switchTab({
        url: '/pages/device/list'
      });
    } catch (error) {
			console.log(error);
		}
	}

  // 登录超时重新登录
  async function uniLoginRefresh(openId) {
    const res = await uni.$api.wxLoginRefresh({openId});
    loginStore.setUserInfo(res.data);
    await loginStore.setAccessToken();
    await uni.switchTab({
      url: '/pages/device/list'
    });
  }

</script>

<style lang="scss" scoped>
	.login {
		padding: 60rpx;
		padding-top: 100rpx;

		.logo {
			width: 246rpx;
			height: 70rpx;
			margin-bottom: 30rpx;
		}

		.username {
			font-size: 26rpx;
			color: #8C8C8C;
		}

		.title {
			font-size: 42rpx;
			font-weight: 700;
			margin-bottom: 60rpx;
		}

		.code {
			text-align: right;
			color: $theme-color;
		}

		.btn {
			margin: 30rpx 0;
		}
	}
</style>

<style lang="scss">
	.login {
		.u-input {
			padding-left: 1px !important;
		}

		.u-border-bottom {
			border-color: $theme-color !important;
		}
	}
</style>
